package cn.lixin.hrm.filter;

import cn.lixin.hrm.MyUserDetailsService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 *  模仿 DaoAuthenticationProvider 重写 authenticate
 */


public class SmsAuthenticationProvider implements AuthenticationProvider {

    //注入UserDetailsService
    private MyUserDetailsService userDetailsService;
    public void setUserDetailService(MyUserDetailsService myUserDetailService){
        this.userDetailsService = myUserDetailService;}
    /**
     *
     * @param authentication --传入的 token
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String phone = authentication.getPrincipal().toString();
        // 如果有手机号单独字段需要重新根据手机号查询
        // 查询到了说明认证成功 将权限放进去
        UserDetails userDetail = userDetailsService.loadUserByUsername(phone);
        return new SmsAuthenticationToken(userDetail.getUsername(),null,userDetail.getAuthorities());
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return (SmsAuthenticationToken.class
                .isAssignableFrom(authentication));
    }
}
